import Mock from 'mockjs'

// 设置随机种子，保证每次生成的数据一致（可选）
// Mock.Random.seed('vue-project-mock')

// 处理带参数的GET请求（如分页）
Mock.mock(/\/api\/users\?page=(\d+)&limit=(\d+)/, 'get', (req: any) => {
  // 从URL中提取参数
  const page = parseInt(req.url.match(/page=(\d+)/)[1])
  const limit = parseInt(req.url.match(/limit=(\d+)/)[1])

  // 模拟分页数据
  return {
    code: 200,
    message: 'success',
    data: {
      total: 100,
      list: Mock.mock({
        [`items|${limit}`]: [
          {
            'id|+1': (page - 1) * limit + 1,
            name: '@cname',
            'age|18-60': 1,
            avatar: '@image("200x200", "#50B347", "#FFF", "Mock.js")',
            email: '@email',
            phone: /^1[3-9]\d{9}$/,
            'status|1': ['active', 'inactive', 'pending'],
            createTime: '@datetime("yyyy-MM-dd HH:mm:ss")',
            address: '@county(true)',
            'role|1': ['admin', 'editor', 'user']
          },
        ],
      }).items,
    },
  }
})

// 获取单个用户详情
Mock.mock(/\/api\/users\/(\d+)/, 'get', (req: any) => {
  const userId = req.url.match(/\/api\/users\/(\d+)/)[1]
  
  return {
    code: 200,
    message: 'success',
    data: {
      id: userId,
      name: '@cname',
      'age|18-60': 1,
      avatar: '@image("200x200", "#50B347", "#FFF", "Mock.js")',
      email: '@email',
      phone: /^1[3-9]\d{9}$/,
      'status|1': ['active', 'inactive', 'pending'],
      createTime: '@datetime("yyyy-MM-dd HH:mm:ss")',
      address: '@county(true)',
      'role|1': ['admin', 'editor', 'user'],
      description: '@csentence(10, 30)',
      lastLoginTime: '@datetime("yyyy-MM-dd HH:mm:ss")',
      'department|1': ['技术部', '市场部', '人力资源部', '财务部', '运营部']
    }
  }
})

// 处理POST请求（创建用户）
Mock.mock('/api/users', 'post', (req: any) => {
  const userData = JSON.parse(req.body)
  
  return {
    code: 200,
    message: '创建成功',
    data: {
      id: Mock.Random.integer(1000, 9999),
      ...userData,
      createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
    }
  }
})

// 处理PUT请求（更新用户）
Mock.mock(/\/api\/users\/(\d+)/, 'put', (req: any) => {
  const userId = req.url.match(/\/api\/users\/(\d+)/)[1]
  const userData = JSON.parse(req.body)
  
  return {
    code: 200,
    message: '更新成功',
    data: {
      id: userId,
      ...userData
    }
  }
})

// 处理DELETE请求（删除用户）
Mock.mock(/\/api\/users\/(\d+)/, 'delete', (req: any) => {
  const userId = req.url.match(/\/api\/users\/(\d+)/)[1]
  
  return {
    code: 200,
    message: '删除成功',
    data: {
      id: userId
    }
  }
})

// 处理登录请求
Mock.mock('/api/login', 'post', (req: any) => {
  // 解析请求体数据
  const { username, password } = JSON.parse(req.body)

  // 模拟登录逻辑
  if (username === 'admin' && password === '123456') {
    return {
      code: 200,
      message: '登录成功',
      data: {
        token: 'mock-token-' + Date.now(),
        userInfo: {
          id: 1,
          name: '管理员',
          avatar: '@image("200x200", "#50B347", "#FFF", "Admin")',
          role: 'admin',
          permissions: ['all']
        }
      }
    }
  } else if (username === 'user' && password === '123456') {
    return {
      code: 200,
      message: '登录成功',
      data: {
        token: 'mock-token-' + Date.now(),
        userInfo: {
          id: 2,
          name: '普通用户',
          avatar: '@image("200x200", "#1890FF", "#FFF", "User")',
          role: 'user',
          permissions: ['read', 'create']
        }
      }
    }
  } else {
    return {
      code: 401,
      message: '用户名或密码错误',
    }
  }
})

// 处理登出请求
Mock.mock('/api/logout', 'post', () => {
  return {
    code: 200,
    message: '登出成功'
  }
})

// 获取用户信息
Mock.mock('/api/user/info', 'get', () => {
  return {
    code: 200,
    message: 'success',
    data: {
      id: 1,
      name: '管理员',
      avatar: '@image("200x200", "#50B347", "#FFF", "Admin")',
      email: 'admin@example.com',
      phone: '13800138000',
      'role|1': ['admin', 'editor', 'user'],
      permissions: ['all'],
      createTime: '@datetime("yyyy-MM-dd HH:mm:ss")',
      lastLoginTime: '@datetime("yyyy-MM-dd HH:mm:ss")'
    }
  }
})

// 模拟产品列表数据
Mock.mock(/\/api\/products\?page=(\d+)&limit=(\d+)/, 'get', (req: any) => {
  const page = parseInt(req.url.match(/page=(\d+)/)[1])
  const limit = parseInt(req.url.match(/limit=(\d+)/)[1])
  
  return {
    code: 200,
    message: 'success',
    data: {
      total: 200,
      list: Mock.mock({
        [`items|${limit}`]: [
          {
            'id|+1': (page - 1) * limit + 1,
            name: '@ctitle(5, 10)',
            price: '@float(10, 1000, 2, 2)',
            originalPrice: '@float(10, 1000, 2, 2)',
            'stock|0-1000': 1,
            'sales|0-10000': 1,
            'status|1': ['on', 'off'],
            coverImage: '@image("400x300", "#50B347", "#FFF", "Product")',
            images: ['@image("400x300", "#50B347", "#FFF", "Image1")', '@image("400x300", "#1890FF", "#FFF", "Image2")'],
            category: '@cword(2, 4)',
            description: '@cparagraph(2, 5)',
            createTime: '@datetime("yyyy-MM-dd HH:mm:ss")'
          }
        ]
      }).items
    }
  }
})

// 模拟订单列表数据
Mock.mock(/\/api\/orders\?page=(\d+)&limit=(\d+)/, 'get', (req: any) => {
  const page = parseInt(req.url.match(/page=(\d+)/)[1])
  const limit = parseInt(req.url.match(/limit=(\d+)/)[1])
  
  return {
    code: 200,
    message: 'success',
    data: {
      total: 150,
      list: Mock.mock({
        [`items|${limit}`]: [
          {
            id: '@string("number", 10)',
            'userId|1-100': 1,
            'totalAmount|100-5000': 1,
            'status|1': ['pending', 'paid', 'shipped', 'delivered', 'cancelled'],
            createTime: '@datetime("yyyy-MM-dd HH:mm:ss")',
            payTime: '@datetime("yyyy-MM-dd HH:mm:ss")',
            'productCount|1-10': 1,
            address: {
              receiver: '@cname',
              phone: /^1[3-9]\d{9}$/,
              province: '@province',
              city: '@city',
              district: '@county',
              detail: '@cparagraph(1, 2)'
            }
          }
        ]
      }).items
    }
  }
})

// 模拟分类数据
Mock.mock('/api/categories', 'get', () => {
  return {
    code: 200,
    message: 'success',
    data: Mock.mock({
      'items|10': [
        {
          'id|+1': 1,
          name: '@cword(2, 4)',
          'parentId|0-5': 0,
          'sort|1-100': 1,
          'level|1-3': 1,
          createTime: '@datetime("yyyy-MM-dd HH:mm:ss")'
        }
      ]
    }).items
  }
})

// 模拟错误响应
Mock.mock('/api/error', 'get', () => {
  return {
    code: 500,
    message: '服务器内部错误',
    data: null
  }
})

// 模拟延迟响应（模拟网络延迟）
Mock.mock('/api/delay', 'get', (req: any, res: any, next: any) => {
  setTimeout(() => {
    next()
  }, 2000)
  return {
    code: 200,
    message: 'success',
    data: {
      delayed: true
    }
  }
})

// 导出Mock供外部使用
export default Mock
